package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: heima-leadnews
 * @description: 创建静态文件
 * @author: ryp
 * @create: 2023-04-30 15:05
 **/
@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;


    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 功能描述: 生成静态文件上传到minIO中
     *
     * @param articleID
     * @return : void
     */
    @Override
    @Async
    public void createStaticUrlTest(Long articleID) throws IOException {
        StringWriter out = new StringWriter();

        try {
            //0. 模拟传递参数
            //Long articleID = 1302862387124125698l;
            // 1)获取静态页面所需文章数据 ap_article_config、ap_article_context
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleID));
            if (apArticleContent == null) {
                return;
            }
            Map<String, Object> result = new HashMap<>();
            String content = apArticleContent.getContent();
            result.put("content", JSONArray.parseArray(content));
            //2) 加载模板，获取模板对象 html--->ftl指令，把页面改成模板
            Template template = configuration.getTemplate("article.ftl");
            //3)生成静态页面2、定义字符流，把字符流输出到minio服务器
            template.process(result, out);
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            //filePath=minio服务器地址+bucket+自定义路径+文件名
            String filePath = fileStorageService.uploadHtmlFile("", articleID + ".html", is);
            //4) 把静态页面地址，写回到数据库
            ApArticle apArticle = new ApArticle();
            apArticle.setStaticUrl(filePath);
            apArticle.setId(apArticleContent.getArticleId());
            apArticleMapper.updateById(apArticle);

            //发送消息，创建索引
            createArticleESIndex(apArticle, content, filePath);
        } catch (IOException e) {
            System.out.println("错误原因：【" + e.getCause() + "】，错误消息提示：【" + e.getMessage() + "】");
        } catch (TemplateException e) {
            System.out.println("错误原因：【" + e.getCause() + "】，错误消息提示：【" + e.getMessage() + "】");
        } finally {
            out.flush();
            out.close();
        }
    }

    /**
     * 功能描述: 发送消息，创建索引
     * @param apArticle
     * @param content
     * @param filePath
     * @return : void
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String filePath) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(filePath);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }
}
